package com.xkstream.client.rx;


import android.util.Log;

import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.BasePresenterImpl;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by zhanghao on 2017/4/22.
 */

public abstract class RxObserver<T> implements Observer<T> {
    private static final String TAG = "RxObserver";

    private BasePresenterImpl presenter;


    public RxObserver(BasePresenterImpl presenter) {
        this.presenter = presenter;
    }

    @Override
    public void onSubscribe(Disposable d) {
        presenter.subscribe(d);
        Log.e(TAG, this.presenter.getClass().getSimpleName());
    }

    @Override
    public void onError(Throwable t) {
        Log.e(TAG, t.getMessage());
        t.printStackTrace();
        onFail(RxException.getErrorMessage(t));
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onNext(T t) {
        if (t instanceof BaseData) {
            BaseData base = (BaseData) t;
            if (base.getCode() == -1) {
                //token过期
                Rxbus.getDefault().post("token_error");
                return;
            }

        }
        onSuccess(t);
    }

    protected abstract void onSuccess(T t);

    protected abstract void onFail(String message);


}
